package com.atguigu.gmall.order.mq;

import com.atguigu.gmall.common.config.mq.service.MqService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.msg.WareOrderMsg;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.order.service.OrderBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static org.reflections.Reflections.log;

/**
 * @Description
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-24 09:17
 **/
@Slf4j
@Component
public class OrderDeduceListener {
    @Autowired
    MqService mqService;
    @Autowired
    OrderBizService orderBizService;

    // 建立库存系统没用创建的交换机和队列[方案1：config里面创建 方案2：注解创建(这里采用该方案)]
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "queue.ware.order", durable = "true", exclusive = "false", autoDelete = "false"),
                    exchange = @Exchange(value = "exchange.direct.ware.order", durable = "true", autoDelete = "false"),
                    key = "ware.order"
            )
    })
    public void deduceStatusListener(Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        
        WareOrderMsg orderMsg = mqService.getMessageContent(message, WareOrderMsg.class);
        try {
            log.info("库存系统扣减结果状态的通知已送达：{}", orderMsg);
            /**
             * 不知道用户id
             *  方式一：改造库存等系统，带上user
             *  方式二：全库全表扫描
             */
            OrderInfo orderInfo = orderBizService.getOrderInfo(orderMsg.getOrderId());
            // 更新订单的库存扣减状态
            orderBizService.updateOrderDeduceStatus(orderInfo.getUserId(), orderInfo.getId(), orderMsg.getStatus());
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            mqService.retry(message, channel, MqConst.ORDER_RETRY_COUNT);
        }
    }
}
